// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Search the bookmarks when entering the search keyword.
// Get the bookmarks and display them in the popup

var server = document.getElementById('server');
chrome.storage.sync.get(['server'], function (result) {
    server.value = result.server;
})

var authDialog = document.getElementById('authDialog');

//同步书签操作
function syncButton() {
    var server = document.getElementById('server').value;
    chrome.bookmarks.getTree((tree) => {
        // displayBookmarks(tree[0].children, document.getElementById('bookmarkList'));
        const bookmarkList = new Array();
        Bookmark2Json(tree[0].children, bookmarkList);
        console.log(JSON.stringify(bookmarkList));
        chrome.runtime.sendMessage({ action: 'sync', data: JSON.stringify(bookmarkList) }, (response) => {
            alert(response);
            //弹出目的地地址
            // chrome.tabs.create({ url: server });
        })
    });
}

// 已知 http[s]://www.baidu.com/abc/path/index.html，获取 http[s]://www.baidu.com
function getDomain(url) {
    //获取前面的协议部分
    // var protocol = url.match(/^(?:https?:\/\/)?/); //获取域名部分
    var domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im);
    return domain[0] + "/favicon.ico";

}

function Bookmark2Json(nodelist, list) {

    nodelist.forEach(nodes => {
        if (nodes.children == undefined) {
            var node = {
                title: nodes.title,
                url: nodes.url,
                id: nodes.id,
                icon: "icon.jpg"
            }
            list.push(node);
        } else {
            var node2 = {
                title: nodes.title,
                id: nodes.id,
                urls: new Array()
            }
            Bookmark2Json(nodes.children, node2.urls);
            list.push(node2);
        }

    });

}
// 保存服务器地址至 storage 中
function SaveServerButton() {
    // 显示认证对话框
    authDialog.showModal();
}

document.getElementById('confirmAuth').addEventListener('click', function (e) {
    e.preventDefault();

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    // 这里添加验证逻辑，这只是一个示例
    if (username && password) {
        // 加入验证用户名和密码.GET请求
        const requestOptions = {
            method: "GET",
            mode: 'cors',  // 添加 CORS 模式
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        };

        const server = document.getElementById('server').value;
        fetch(server + "/login?username=" + username + "&password=" + password + "&flag=1", requestOptions)
            .then(response => {
                if (!response.ok) {
                    throw new Error('认证失败');
                }
                return response.text();
            })
            .then(result => {
                console.log("认证成功");
                // 将用户名和密码合并并进行base64编码
                const authString = btoa(username + ':' + password);
                // 保存服务器地址和认证信息
                chrome.storage.sync.set({
                    'server': server,
                    'auth': authString
                }, function () {
                    alert('保存成功');
                    authDialog.close();
                });
            })
            .catch(error => {
                alert("认证失败,请检查用户名和密码");
                throw error;
            });
    } else {
        alert('请输入用户名和密码');
    }
});

document.getElementById('cancelAuth').addEventListener('click', function () {
    authDialog.close();
});

document.getElementById('saveServer').addEventListener('click', SaveServerButton);
document.getElementById('syncButton').addEventListener('click', syncButton);
